package app.projeto.dao;

import java.sql.ResultSet;
import java.sql.Statement;

import app.projeto.entity.Membro;
import app.projeto.entity.Usuario;
import app.projeto.util.Factory;
import app.projeto.util.Query;

public class DaoMembro extends Dao{
	
	@Override
	public void save(Object obj) throws Exception {
		try {
			String sql = Query.getSQLInsert(obj);
			System.out.println(sql);
			Statement stmt = this.getConnection().createStatement();
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			throw e;
		}
	}
	
	@Override
	public void delete(Object obj) throws Exception {
		try {
			String sql = "delete from " + Query.getTableName(obj) + " " + Query.getSQLWhere(obj);
			System.out.println(sql);
			Statement stmt = this.getConnection().createStatement();
			stmt.executeUpdate(sql);
		} catch (Exception e) {
			this.rollback();
			throw e;
		}
	}
	
	/**
	 * Busca o membro pelo usuario
	 * 
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public Object[] findByUser(Object obj) throws Exception {
		Usuario usuario = (Usuario) obj;
		Membro membro = new Membro();
		try {
			String sql = "select " + Query.getFieldNames(membro,true) +
					" from " + Query.getTableName(membro)  + " " +
					" where idusuario = " + usuario.getIdUsuario();
			System.out.println(sql);
			Statement stmt = this.getConnection().createStatement();
			ResultSet rst = stmt.executeQuery(sql);
			return Factory.createByResultSet(rst, membro.getClass());
		} catch (Exception e) {
			this.rollback();
			throw e;
		}
	}
}
